package com.wie.interceptor;


import com.wie.BaseContext.BaseContext;
import com.wie.constant.MessageConstant;
import com.wie.exception.NotLoginException;
import com.wie.properties.JwtProperties;
import com.wie.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Slf4j
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String method = request.getMethod();
        log.info("本次请求方式为：{}", method);
        if("OPTIONS".equals(method)) {
            return true;
        }

        // 获取请求url
        String url = request.getRequestURI().toString();
        log.info("请求的URL：{}", url);
        // 判断是否为登录请求
        if(url.contains("login") || url.contains("sendCode") || url.contains("signup")) {
            log.info("放行");
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getTokenName());   

        //2、校验令牌
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getSignKey(), token);
            //3、通过，放行
            Integer userId = Integer.valueOf(claims.get("userId").toString());
            BaseContext.setCurrentId(userId);
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            response.setStatus(401);
            throw new NotLoginException(MessageConstant.NOT_LOGIN);
        }
    }
}
